import requests
from django.conf import settings
import json
from typing import Optional, Dict, Any, List

class AIService:
    def __init__(self):
        self.url = "https://api.siliconflow.cn/v1/chat/completions"
        self.api_key = getattr(settings, 'AI_API_KEY', 'sk-pvibdzgjvaiqwzuikkltbfupjqewalvptylzabtjkvnujtry')
        self.model = getattr(settings, 'AI_MODEL', 'Qwen/Qwen3-8B')
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def get_chat_response(self, messages: List[Dict[str, str]]) -> Optional[Dict[str, Any]]:
        """
        获取AI聊天响应
        
        Args:
            messages: 包含多轮对话历史的列表，每个元素是一个字典，包含'role'和'content'
            
        Returns:
            Dict包含AI响应，如果发生错误则返回None
        """
        try:
            payload = {
                "model": self.model,
                "messages": messages, # 使用传入的messages列表
                "stream": False,
                "max_tokens": 512,
                "enable_thinking": False,
                "thinking_budget": 4096,
                "min_p": 0.05,
                "stop": None,
                "temperature": 0.7,
                "top_p": 0.7,
                "top_k": 50,
                "frequency_penalty": 0.5,
                "n": 1,
                "response_format": {"type": "text"},
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "description": "<string>",
                            "name": "<string>",
                            "parameters": {},
                            "strict": False
                        }
                    }
                ]
            }

            response = requests.post(self.url, json=payload, headers=self.headers)
            response.raise_for_status()  # 如果响应状态码不是200，将引发异常
            
            return response.json()
            
        except requests.RequestException as e:
            print(f"AI API请求错误: {str(e)}")
            return None
        except json.JSONDecodeError as e:
            print(f"解析AI响应JSON错误: {str(e)}")
            return None
        except Exception as e:
            print(f"未知错误: {str(e)}")
            return None

# 创建单例实例
ai_service = AIService()